package com.zygh.lz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.dao.AccountMapper;
import com.zygh.lz.dao.SignboardMapper;
import com.zygh.lz.entity.Account;
import com.zygh.lz.entity.AccountConfig;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.role.SysUserRole;
import com.zygh.lz.entity.signfile.SignBoard;
import com.zygh.lz.service.AccountConfigService;
import com.zygh.lz.service.AccountService;
import com.zygh.lz.service.role.SysUserRoleServiceImpl;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.SysLogAspect;
import com.zygh.lz.util.JwtUtils;
import com.zygh.lz.util.Md5;
import com.zygh.lz.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Resource
    private SignboardMapper signboardMapper;
    @Resource
    private SysUserRoleServiceImpl sysUserRoleService;

    @Resource
    AccountConfigService accountConfigService;

    @Override
    public ResultBean sel(Account account) {
        PageHelper.startPage(account.getPageNum(), account.getPageSize());

        List<Map> select = accountMapper.select(account);
        PageInfo<Map> page = new PageInfo<>(select);
        return ResultUtil.setOK("查询成功", page);
    }

    @Override
    public ResultBean add(@RequestBody Account account) {
        int insert = accountMapper.insert(account);
        Account account1 = accountMapper.selectOne(Wrappers.<Account>lambdaQuery().eq(Account::getStaffTel, account.getStaffTel()));

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId((long) account1.getSysStaffId());
        sysUserRole.setRoleId((long) account1.getSysRoleId());
        sysUserRoleService.save(sysUserRole);
        AccountConfig accountConfig = new AccountConfig();
        accountConfig.setSysStaffId(account1.getSysStaffId());
        accountConfigService.save(accountConfig);
        return ResultUtil.setOK("新增成功", null);
    }

    @Override
    public ResultBean del(@RequestBody Account account) {
        int i = accountMapper.deleteById(account.getId());
        return ResultUtil.setOK("删除成功", null);
    }

    @Override
    public ResultBean update(@RequestBody Account account) {
        accountMapper.update(account, Wrappers.<Account>lambdaUpdate().eq(Account::getSysStaffId, account.getSysStaffId()));

        sysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, account.getSysStaffId()));

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId((long) account.getSysStaffId());
        sysUserRole.setRoleId((long) account.getSysRoleId());
        sysUserRoleService.save(sysUserRole);

        return ResultUtil.setOK("修改成功", null);
    }

    @Override
    public List<Map<String, Object>> selByRoles(Long[] ids) {
        List<Map<String, Object>> maps = accountMapper.selectMaps(Wrappers.<Account>lambdaQuery().in(Account::getSysRoleId, ids));
        return maps;
    }

    @Override
    public ResultBean selectByLogin(String staff_tel, String staff_password) {
        //加密
        staff_password = Md5.MD5Encode(staff_password, "utf-8");
        //根据用户密码查询
        Account staff = accountMapper.selectByLogin(staff_tel, staff_password);
        if (staff != null) {
            //实现单点登录
            getPcIp(staff_tel);
            // 生成jwt，并放置到请求头中
            String jwt = jwtUtils.generateToken(staff_tel);

            return ResultUtil.setOK("登录成功", jwt);
        }
        return ResultUtil.setOK("登录失败", null);
    }

    @Override
    public Account selByStaffTel(String staffTel) {
        return accountMapper.selectOne(Wrappers.<Account>lambdaQuery().eq(Account::getStaffTel, staffTel));
    }

    @Override
    public Account getByUsername(String username) {
        return accountMapper.selectOne(Wrappers.<Account>lambdaQuery().eq(Account::getStaffTel, username));
    }

    @Override
    public ResultBean modifuByPass(Account account) {
        //加密
        account.setStaffPassword(Md5.MD5Encode(account.getStaffPassword(), "utf-8"));
        account.setSysStaffId(account.getId());
        int i = accountMapper.updateById(account);
        if (i > 0) {
            return ResultUtil.execOp(1, "修改密码");
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    private void getPcIp(String staff_tel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //判断是PC还是APP
        String ua = request.getHeader("User-Agent");
        //PC端访问存起来，APP过滤掉
        if (!SysLogAspect.checkAgentIsMobile(ua)) {
            String remoteIP = SysLogAspect.getRemoteIP(request);
            System.out.println(staff_tel + "获取到的ip：" + remoteIP);
            String[] split = remoteIP.split("\\.");
            if (split.length == 4) {
                Integer integer = signboardMapper.selectCount(Wrappers.<SignBoard>lambdaQuery()
                        .eq(SignBoard::getName, staff_tel));
                SignBoard signBoard = new SignBoard();
                signBoard.setName(staff_tel);
                signBoard.setIp(remoteIP);
                signBoard.setCreateTime(new Date());
                if (integer >= 2) {
                    int delete = signboardMapper.delete(Wrappers.<SignBoard>lambdaQuery()
                            .eq(SignBoard::getName, staff_tel)
                            .orderByAsc(SignBoard::getCreateTime)
                            .last("limit 1"));
                    if (delete == 1) {

                        signboardMapper.insert(signBoard);
                    }
                } else {
                    signboardMapper.insert(signBoard);
                }

            }
        }
    }

}
